﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace Sliver.Core.Event
{
    public class CarcassonneTimer : MonoBehaviour
    {
        public static CarcassonneTimer Instance;

        protected SortedList<float, List<UnityAction>> DelayActions = new SortedList<float, List<UnityAction>>();

        protected List<float> DiscardActions = new List<float>();

        protected void Awake()
        {
            Instance = this;
            GameObject.DontDestroyOnLoad(this);
        }

        protected void Update()
        {
            float now = Time.time;
            foreach (var kv in DelayActions)
            {
                float triggerTime = kv.Key;
                if (now >= triggerTime)
                {
                    foreach (UnityAction action in kv.Value)
                    {
                        action.Invoke();
                    }
                    DiscardActions.Add(triggerTime);
                }
                else
                {
                    break;
                }
            }

            foreach (float key in DiscardActions)
            {
                DelayActions.Remove(key);
            }
            DiscardActions.Clear();
        }

        public void CallDelay(float delay, UnityAction action)
        {
            float triggerTime = Time.time + delay;
            if (!DelayActions.ContainsKey(triggerTime))
            {
                List<UnityAction> list = new List<UnityAction>();
                list.Add(action);
                DelayActions.Add(triggerTime, list);
            }
            else
            {
                DelayActions[triggerTime].Add(action);
            }
        }
    }
}
